package com.taplinker.client.im.rpc;

import android.os.Handler;

import com.google.protobuf.InvalidProtocolBufferException;
import com.taplinker.client.core.TaplinkerApplication;
import com.taplinker.core.rpc.socket.IMessageResponse;
import com.taplinker.core.rpc.socket.SocketConfigContext;
import com.taplinker.core.rpc.socket.SocketTemplate;
import com.taplinker.core.rpc.socket.channel.ChannelContext;
import com.taplinker.core.util.LogUtil;
import com.taplinker.dto.web.MessageResponseProto.MessageResponse;

public class ImSocketTemplate extends SocketTemplate {
	private Handler handle = null;
	
	public ImSocketTemplate(SocketConfigContext scontext) {
		super(scontext,new ReceiveHandler());
		handle = new Handler();
	}
	
	@Override
	public void exceptionCaught(ChannelContext ctx, Exception e) {
		super.exceptionCaught(ctx, e);
		if(handle != null)
			handle.post(new Runnable() {
				
				@Override
				public void run() {
//					Toast.makeText(AppConfigFactory.getInstance().getApplication(),"网络已断开", 0).show();
					TaplinkerApplication.getInstance().logOut();
				}
			});
	}
	
	@Override
	protected IMessageResponse convert(byte[] response) {
		try {
			IMMessageResponse result = new IMMessageResponse(MessageResponse.parseFrom(response));
			LogUtil.d("socket receive", result.getMessage().getBody());
			return result;
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		return null;
	}
}
